package com.itmgg.web.task;

import com.google.gson.Gson;
import com.itmgg.web.activiti.service.WorkFlowService;
import com.itmgg.web.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.util.Map;

@Slf4j
@Component
@EnableScheduling
public class TimeTask {
    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private Gson gson;

    // 5秒推送一次
    @Scheduled(cron = "*/20 * * * * ?")
    public void sendMsg() {
        log.info("**********定时任务执行***********");
        Map<String, Map<String, Session>> webSocketSet = webSocketServer.getWebSocketSet();
        if (MapUtils.isEmpty(webSocketSet)) {
            log.info("定时任务执行流程实例 webSocketSet为空=================================");
            return;
        }
        for (Map.Entry<String, Map<String, Session>> entry : webSocketSet.entrySet()) {
            String instanceId = entry.getKey();
            Map<String, Object> highLine = workFlowService.getHighLine(instanceId);
            log.info("定时任务执行流程实例instanceId====================={}", instanceId);
            Map<String, Session> sessionMap = entry.getValue();
            // 同一个实例id只用查一次流程图 然后循环所有session广播
            for (Map.Entry<String, Session> sessionEntry : sessionMap.entrySet()) {
                String socketId = sessionEntry.getKey();
                Session session = sessionEntry.getValue();
                log.info("定时任务执行流程实例instanceId:{}====socketId={}", instanceId, socketId);
                log.info("定时任务执行流程实例session{}", session);
                if (session != null) {
                    try {
                        if (MapUtils.isNotEmpty(highLine)) {
                            session.sendText(gson.toJson(highLine));
                        }
                    } catch (Exception e) {
                        log.error("定时任务执行流程实例instanceId:{}====socketId={},发送消息失败", instanceId, socketId);
                    }
                }
            }
        }
    }
}

